package cn.sciento.boot.api.customize.compile;

import java.util.HashMap;
import java.util.Map;

public class DynamicClassLoader extends ClassLoader {
  private final Map<String, MemoryByteCode> byteCodes = new HashMap<>();
  
  public DynamicClassLoader(ClassLoader classLoader) {
    super(classLoader);
  }
  
  public void registerCompiledSource(MemoryByteCode byteCode) {
    this.byteCodes.put(byteCode.getClassName(), byteCode);
  }
  
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    MemoryByteCode byteCode = this.byteCodes.get(name);
    if (byteCode == null)
      return super.findClass(name); 
    return defineClass(name, byteCode.getByteCode(), 0, (byteCode.getByteCode()).length);
  }
  
  public Map<String, Class<?>> getClasses() throws ClassNotFoundException {
    Map<String, Class<?>> classes = new HashMap<>();
    for (MemoryByteCode byteCode : this.byteCodes.values())
      classes.put(byteCode.getClassName(), findClass(byteCode.getClassName())); 
    return classes;
  }
  
  public Map<String, byte[]> getByteCodes() {
    Map<String, byte[]> result = (Map)new HashMap<>(this.byteCodes.size());
    for (Map.Entry<String, MemoryByteCode> entry : this.byteCodes.entrySet())
      result.put(entry.getKey(), ((MemoryByteCode)entry.getValue()).getByteCode()); 
    return result;
  }
}
